<?php

namespace backend\controllers;


use backend\utils\AppUtil;
use PHPExcel_Style_NumberFormat;
use yii\web\Controller;
use yii\helpers\Url;
use Yii;

class DownMultiSheetController extends Controller
{
    /**
     * @desc 导出 down-multi-sheet/export-data1
     * @return void
     * @Date: 2024/11/6
     */
    public function actionExportData1()
    {
        //lsc_recommend.type '类型:1 学历继续教育;2 非学历继续教育;3 院校三教统筹;4 地市级/省级三教统筹',
        //学历继续教育
        $infos = [
            1 => '继续教育品牌特色专业（群）建设',
            2 => '继续教育课程思政与思政课程建设',
            3 => '线上线下相结合的精品课程建设',
            4 => '体现继续教育特点的新形态教材建设',
            5 => '专业化、服务型教学创新团队建设',
            6 => '教育教学模式创新',
            7 => '数字化优质资源共建共享建设',
            8 => '办学全链条、全过程管理体系建设',
            9 => '数字化学习支持服务建设',
        ];
        $model_names = [
            1 => ['LscTAcademicProject1'],
            2 => ['LscTAcademicProject2', 'LscTAcademicProject2Detail'],
            3 => ['LscTAcademicProject3', 'LscTAcademicProject3Detail'],
            4 => ['LscTAcademicProject4', 'LscTAcademicProject4Detail'],//
            5 => ['LscTAcademicProject5', 'LscTAcademicProject5Honors'],
            6 => ['LscTAcademicProject6Major', 'LscTAcademicProject6Course'],
            7 => ['LscTAcademicProject7'],
            8 => ['LscTAcademicProject8'],
            9 => ['LscTAcademicProject9'],
        ];
        $function_name = 'get_academic_titles_and_data';
        $this->exportData($infos, $model_names, $function_name, '学历继续教育');
        exit();
    }

    public function exportData($infos, $model_names, $function_name, $type_t)
    {
        require_once Url::to('@common') . '/extensions/PHPExcel-1.8/Classes/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        // 设置默认样式
        $objPHPExcel->getDefaultStyle()->getFont()->setName(AppUtil::FONT_NAME);
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(AppUtil::FONT_SIZE);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);//自动换行
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        $sheet_index = 0;
        foreach ($infos as $k => $v) {
            // LscTProjectBasicInfo
            $sql = "select uuid from lsc_t_project_basic_info where construction_content_type like '%{$k}%' ";
            $basic_info_ids = \Yii::$app->db->createCommand($sql)->queryColumn();

            $model_name_arr = $model_names[$k];
            foreach ($model_name_arr as $model_name_k => $model_name) {
                $model_name_k = count($model_name_arr) > 1 ? $k . '.' . ($model_name_k + 1) : '';
                $model = '\backend\models\lsc\\' . $model_name;//
                $model = Yii::createObject(['class' => $model]);

                $sheet = $objPHPExcel->getActiveSheet($sheet_index);
                if ($sheet_index > 0) {
                    $objPHPExcel->createSheet();
                    $sheet = $objPHPExcel->setactivesheetindex($sheet_index);
                }
                $sheet->setTitle($v . $model_name_k);

                list($fields, $data) = $model->$function_name($basic_info_ids);

                $title = ['序号', '省名称', '学校名称', '学校类型'];
                $title = array_merge($title, array_values($fields));
                foreach ($title as $title_k => $title_t) {
                    $col = \PHPExcel_Cell::stringFromColumnIndex($title_k);// A B C D ...
                    $sheet->getColumnDimension($col)->setWidth($title_k == 0 ? 8 : 20);
                    $sheet->getStyle("A1:{$col}1")->getFont()->setBold(true);
                    $sheet->setCellValueByColumnAndRow($title_k, 1, $title_t);
                }

                $row = 2;
                $min_width = 15;
                $max_width = 120;
                $widths = [];
                $col = "A";
                foreach ($data as $key => $val) {
                    $cell_index = 0;
                    $unit_type_t = LscUnit::get_unit_type_t($val['unit_type'], $val['other_type']);
                    $sheet->setCellValueByColumnAndRow($cell_index++, $row, $key + 1);
                    $sheet->setCellValueByColumnAndRow($cell_index++, $row, $val['province_name']);//省名称
                    $sheet->setCellValueByColumnAndRow($cell_index++, $row, $val['unit_name']);//学校名称
                    $sheet->setCellValueByColumnAndRow($cell_index++, $row, $unit_type_t);//学校类型
                    //
                    foreach ($fields as $field => $field_t) {
                        if (in_array($field, ['major_code'])) {
                            $col = \PHPExcel_Cell::stringFromColumnIndex($cell_index);// A B C D ...
                            // 处理 内蒙古开放大学 major_code => 240301459010110 在excel里变成 2.40301E+14
                            $sheet->getStyle($col . $row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
                        }
                        $cell_val = $val[$field];
                        //$cell_val = nl2br($cell_val);
                        $cell_val = preg_replace('/<[^>]+>/', '', $cell_val);//去掉html标签
                        $cell_val = str_replace(['&nbsp;'], '', $cell_val);//去掉空格
                        $sheet->setCellValueByColumnAndRow($cell_index++, $row, $cell_val);

                        // --- 设置表格的动态列宽 start ------
                        $cell_val_len = mb_strlen($cell_val, 'utf-8');// 字符长度函数
                        if (!isset($widths[$field])) {
                            // 设置列宽初始值 $min_width
                            $widths[$field] = $min_width;
                        }
                        if ($cell_val_len > $widths[$field]) {
                            // 最大列宽不超过 $max_width
                            $widths[$field] = $cell_val_len > $max_width ? $max_width : $cell_val_len;
                        }
                        $col = \PHPExcel_Cell::stringFromColumnIndex($cell_index - 1);
                        $sheet->getColumnDimension($col)->setWidth($widths[$field]);
                        // --- 设置表格的动态列宽 END ------
                    }

                    $row++;
                }
                // 加上边框
                $sheet->getStyle("A1:{$col}" . ($row - 1))->applyFromArray(AppUtil::$excel_all_borders);

                $sheet_index++;
            }
            //if ($k == 1) break;
        }

        $objPHPExcel->setActiveSheetIndex(0);
        $filename = iconv("utf-8", "gb2312//TRANSLIT", $type_t . '数据情况' . '.xlsx');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;Charset=utf-8;');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        die();
    }

}
